<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class HAuth extends CI_Controller
{
	public function __construct()
	{
		parent::__construct();
		$this->load->library('session');
	}
	
	public function login($provider)
	{
		try
		{
			// Load HybridAuthLib
			$this->load->library('HybridAuthLib');

			if ($this->hybridauthlib->serviceEnabled($provider))
			{
				// Authenticate
				$service = $this->hybridauthlib->authenticate($provider);

				if ($service->isUserConnected())
				{
					// Get user profile
					$user_profile = $service->getUserProfile();
					$data['user_profile'] = $user_profile;
					
					// Do we already know each other?
					
					// Load user model
					$this->load->model('users_model', 'users');
					
					// Facebook and Google have email in parameters...
					if($data['user_profile']->email)
					{
						$user = $this->users->get_by_email($data['user_profile']->email);
					}
					// While Twitter does not.
					else
					{
						$user = $this->users->get_by_twitter_id($data['user_profile']->identifier);
					}
					
					if($user)
					{
						// Update data?
						$flag = false;
						
						if(!$user->firstname && $data['user_profile']->firstName)
						{
							$flag = true;
							$user->firstname = $data['user_profile']->firstName;
						}
						
						if(!$user->lastname && $data['user_profile']->lastName)
						{
							$flag = true;
							$user->lastname = $data['user_profile']->lastName;
						}
						
						if($flag)
						{
							$this->users->update($user);
						}

						// Set session
						$this->session->set_userdata('logged_in', TRUE);
						
						// Redirect to home page
						header('Location: /home');
					}
					else
					{
						// Facebook and Google have email in parameters...
						if($data['user_profile']->email)
						{
							$this->session->set_userdata('connect', array('email' => $data['user_profile']->email));
						}
						// While Twitter does not.
						else
						{
							$this->session->set_userdata('connect', array('twitter_id' => $data['user_profile']->identifier));
						}
						
						header('Location: /auth/signin');
					}

				}
				else // Cannot authenticate user
				{
					show_error('Cannot authenticate user');
				}
			}
			else // This service is not enabled.
			{
				show_404($_SERVER['REQUEST_URI']);
			}
		}
		catch(Exception $e)
		{
			$error = 'Unexpected error';
			switch($e->getCode())
			{
				case 0 : $error = 'Unspecified error.'; break;
				case 1 : $error = 'Hybriauth configuration error.'; break;
				case 2 : $error = 'Provider not properly configured.'; break;
				case 3 : $error = 'Unknown or disabled provider.'; break;
				case 4 : $error = 'Missing provider application credentials.'; break;
				case 5 : log_message('debug', 'controllers.HAuth.login: Authentification failed. The user has canceled the authentication or the provider refused the connection.');
				         //redirect();
				         if (isset($service))
				         {
				         	log_message('debug', 'controllers.HAuth.login: logging out from service.');
				         	$service->logout();
				         }
				         show_error('User has cancelled the authentication or the provider refused the connection.');
				         break;
				case 6 : $error = 'User profile request failed. Most likely the user is not connected to the provider and he should to authenticate again.';
				         break;
				case 7 : $error = 'User not connected to the provider.';
				         break;
			}

			if (isset($service))
			{
				$service->logout();
			}

			log_message('error', 'controllers.HAuth.login: '.$error);
			show_error('Error authenticating user. '.$error);
		}
	}
	
	public function view()
	{
		// Check for session
		if($this->session->userdata('logged_in'))
		{
			// Signed in - redirect to home page
			header('Location: /home');
		}
		
		// Title
		$data['title'] = 'Teretulemast!';
		
		// Connect?
		if($this->session->userdata('connect'))
		{
			$connect_data = $this->session->userdata('connect');
			if(array_key_exists('email', $connect_data))
			{
				$data['email'] = $connect_data['email'];
			}
			
			$data['connect'] = true;
		}
		else
		{
			$data['connect'] = false;
		}
		
		// Main navigation
		$data['main_navigation'] = $this->load->view('main-navigation', array('logged_in' => FALSE), true);
		
		// URL
		$this->load->helper('url');
		
		// Show
		$this->load->view('templates/header', $data);
		$this->load->view('signin', $data);
		$this->load->view('templates/footer', $data);
	}
	
	public function signout()
	{
		// Check for session
		if($this->session->userdata('logged_in'))
		{
			// Unset
			$this->session->unset_userdata('logged_in');
		}
		
		// Redirect to home page
		header('Location: /home');
	}

	public function endpoint()
	{
		log_message('debug', 'controllers.HAuth.endpoint called.');
		log_message('info', 'controllers.HAuth.endpoint: $_REQUEST: '.print_r($_REQUEST, TRUE));

		if ($_SERVER['REQUEST_METHOD'] === 'GET')
		{
			log_message('debug', 'controllers.HAuth.endpoint: the request method is GET, copying REQUEST array into GET array.');
			$_GET = $_REQUEST;
		}

		log_message('debug', 'controllers.HAuth.endpoint: loading the original HybridAuth endpoint script.');
		require_once APPPATH.'/third_party/hybridauth/index.php';
	}

}

/* End of file test.php */
/* Location: ./application/controllers/test.php */